<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class PromotionController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:web');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //查询用户推广数据
        $promotion = DB::table('promotion')
            ->select('id', 'url', 'code', 'single', 'total', 'start_date', 'end_date', 'state','promoter')
            ->where( 'promoter',Auth::user()->username)
            ->where(function ($query) {
                $query->orWhere('url', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('code', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('single', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('total', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('start_date', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('end_date', 'like', '%'.@$_GET['search'].'%');
            })
            ->orderBy('id', 'desc')
            ->paginate(15)
            ->withPath('promotion?search=' . @$_GET['search'] . '');

        return view('user.promotion.index',['promotion'=>$promotion]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('user.promotion.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        //验证表单
        $this->validate($request, [
            'url' => ['required','url','max:30'],
            'single' => ['required','string','max:8'],
            'total' => ['required','string','max:8'],
            'start_date' => ['required','date','max:10'],
            'end_date' => ['required','date','max:10'],
            'state' => ['required','string','max:1'],
        ]);

        if( Auth::user()->money < $request->total){
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['money' => ['账户余额不足。']]], 422);
        }

        //扣除账户金额
        DB::table('users')
            ->where('id', Auth::id())
            ->decrement('money', $request->total);

        //写入添加的游戏
        DB::table('promotion')->insert([
            'url' => $request->url,
            'code' => substr(md5(uniqid(mt_rand(), TRUE)),8,16),
            'single' => $request->single,
            'total' => $request->total,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'state' => $request->state,
            'promoter' => Auth::user()->username
        ]);

        return response()->json(['message' => '添加成功。', 'success' => 'true']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //获取商城物品信息
        $item = DB::table('promotion')->select('id', 'url', 'single', 'total', 'start_date', 'end_date', 'state','promoter')
            ->where('id', $id)
            ->get();

        //如果没有找到符合的商品信息
        if ( !$item->count() ) {
            return redirect()->route('promotion.index');
        }else{
            return view('user.promotion.edit', [
                'item' => $item
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        //验证表单
        $this->validate($request, [
            'url' => ['required','url','max:30'],
            'single' => ['required','string','max:8'],
            'total' => ['nullable','string','max:8'],
            'start_date' => ['required','date','max:10'],
            'end_date' => ['required','date','max:10'],
            'state' => ['required','string','max:1'],
        ]);

        if (!$request->total){
            $request->total = 0;
        }

        if( Auth::user()->money < $request->total){
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['money' => ['账户余额不足。']]], 422);
        }

        //扣除账户金额
        DB::table('users')
            ->where('id', Auth::id())
            ->decrement('money', $request->total);

        //更新游戏信息
        DB::table('promotion')
            ->where('id', $id)
            ->where('promoter', Auth::user()->username)
            ->update([
                'url' => $request->url,
                'single' => $request->single,
                'total' => DB::raw('total+ '.$request->total.''),
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'state' => $request->state
            ]);

        return response()->json(['message' => '编辑成功。', 'success' => 'true']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        $promotion = DB::table('promotion')
            ->whereIn('id', explode(',', $id))
            ->sum('total');

        DB::table('promotion')
            ->whereIn('id', explode(',', $id))
            ->delete();

        DB::table('users')
            ->where('username', Auth::user()->username)
            ->increment('money', $promotion);

        return response()->json(['message' => '删除成功！剩余额度'.$promotion.'元。将转到账户余额。', 'success' => 'true']);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function record()
    {
        //查询用户推广数据
        $promotion_record = DB::table('promotion_record')
            ->select('id', 'url', 'ip', 'address', 'single', 'total', 'time','income_person')
            ->where( 'promoter',Auth::user()->username)
            ->where(function ($query) {
                $query->orWhere('url', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('ip', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('address', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('time', 'like', '%'.@$_GET['search'].'%');
            })
            ->orderBy('id', 'desc')
            ->paginate(18)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('user.promotion.record',['promotion_record'=>$promotion_record]);
    }
}
